<script>
export default {
  name: 'GFormCreator',
  props: {
    config: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      formData: {}
    }
  },
  created () {
    const { fields } = this.config
    fields.forEach((rowArr) => {
      rowArr.forEach((item) => {
        this.$set(this.formData, item.key, '')
      })
    })
  },
  render () {
    const { fields: items } = this.config
    return (
      <div>
        <el-form ref="form" label-width="80px">
          {this.renderItems(items)}
        </el-form>
        {this.renderBtn()}
      </div>
    )
  },
  methods: {
    renderFormItem (item) {
      switch (item.type) {
        case 'text':
        case 'password':
        case 'textarea':
          return (
            <el-input
              type={item.type}
              value={this.formData[item.key]}
              onInput={(e) => (this.formData[item.key] = e)}
            />
          )
        case 'select':
          return (
            <el-select attrs={item.attrs} v-model={this.formData[item.key]}>
              {item.options.map((option) => {
                return (
                  <el-option
                    label={option.label}
                    value={option.value}
                  ></el-option>
                )
              })}
            </el-select>
          )
      }
      return <el-input />
    },
    renderColumns (columns) {
      return columns.map((col) => {
        return (
          <el-col span={col.colspan}>
            <el-form-item label={col.label} prop={col.key}>
              {this.renderFormItem(col)}
            </el-form-item>
          </el-col>
        )
      })
    },
    renderItems (items) {
      return items.map((rowArr) => {
        return <el-row>{this.renderColumns(rowArr)}</el-row>
      })
    },
    getData () {
      return this.formData
    },
    submitForm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('submit', this.getData)
        } else {
          console.log('error!!')
        }
      })
    },
    renderBtn () {
      const { default: defaultSlot } = this.$scopedSlots
      // 是否传递了默认插槽
      if (defaultSlot) {
        return defaultSlot({ innerValue: '组件内部回传' })
      } else {
        return (
          <div>
            <el-button type="success" onClick={this.submitForm}>
              确定
            </el-button>
            <el-button>重置</el-button>
          </div>
        )
      }
    }
  }
}
</script>
